package cn.iocoder.yudao.module.enterprise.controller.admin.company;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.alibaba.IdAuthenticationUtils;
import cn.iocoder.yudao.framework.common.util.encryption.EncryptionUtil;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.enterprise.controller.admin.company.vo.*;
import cn.iocoder.yudao.module.enterprise.convert.company.EnterpriseCompanyConvert;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.company.EnterpriseCompanyDO;
import cn.iocoder.yudao.module.enterprise.service.company.EnterpriseCompanyService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.USER_NOT_EXISTS;

@Api(tags = "管理后台 -企业端- 企业信息")
@RestController
@RequestMapping("/enterprise/company")
@Slf4j
public class EnterpriseCompanyController {

    @Resource
    private EnterpriseCompanyService companyService;
    @Resource
    private AdminUserApi adminUserApi;
    @PostMapping("/create")
    @ApiOperation("创建企业信息")
    public CommonResult<Long> createCompany( @RequestBody CompanyCreateReqVO createReqVO) {
        return success(companyService.createCompany(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新企业介绍信息")
    public CommonResult<Boolean> updateCompany( @RequestBody CompanyUpdateReqVO updateReqVO) {
        companyService.updateCompany(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除企业信息")
    public CommonResult<Boolean> deleteCompany(@RequestParam("id") Long id) {
        companyService.deleteCompany(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得企业介绍信息")
    public CommonResult<CompanyRespVO> getCompany(@RequestParam("id") Long id) {
        EnterpriseCompanyDO company = companyService.getCompany(id);
        return success(EnterpriseCompanyConvert.INSTANCE.convert(company));
    }

    @GetMapping("/compant-get")
    @ApiOperation("获得企业介绍信息")
    public CommonResult<CompanyRespVO> getCompany() {
        EnterpriseCompanyDO company;
        Long companyId=SecurityFrameworkUtils.getLoginUser().getCompanyId();
        if(companyId!=null){
             company = companyService.getCompany(companyId);

        }else {
            company = companyService.getCompanyByphone(SecurityFrameworkUtils.getLoginUser().getUsername());
        }
        CompanyRespVO convert = EnterpriseCompanyConvert.INSTANCE.convert(company);
        return success(convert);
    }

    @GetMapping("/getCompanyByLoginUser")
    @ApiOperation("获得企业介绍信息")
    @TenantIgnore
    public CommonResult<CompanyRespVO> getCompanyByLoginUser() {
        LoginUser loginUser=SecurityFrameworkUtils.getLoginUser();
        log.info("getCompanyByLoginUser--->"+SecurityFrameworkUtils.getLoginUser().getUsername());
        if(loginUser.getTenantId()==0){
            return null;
        }
        if(loginUser.getCompanyId()==null){
            return null;
        }
        EnterpriseCompanyDO company = companyService.getCompanyByLoginUser(loginUser.getCompanyId());

        return success(EnterpriseCompanyConvert.INSTANCE.convert(company));
    }


    @GetMapping("/list")
    @ApiOperation("获得企业信息列表")
    public CommonResult<List<CompanyRespVO>> getCompanyList(@RequestParam("ids") Collection<Long> ids) {
        List<EnterpriseCompanyDO> list = companyService.getCompanyList(ids);
        return success(EnterpriseCompanyConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得企业信息分页")
    public CommonResult<PageResult<CompanyRespVO>> getCompanyPage( @RequestBody CompanyPageReqVO pageVO) {
        PageResult<EnterpriseCompanyDO> pageResult = companyService.getCompanyPage(pageVO);
        return success(EnterpriseCompanyConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出企业信息 Excel")
    @OperateLog(type = EXPORT)
    public void exportCompanyExcel( CompanyExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<EnterpriseCompanyDO> list = companyService.getCompanyList(exportReqVO);
        // 导出 Excel
        List<CompanyExcelVO> datas = EnterpriseCompanyConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "企业信息.xls", "数据", CompanyExcelVO.class, datas);
    }
    @PostMapping("/askAuthentication")
    @ApiOperation("企业申请认证")
    public CommonResult<CompanyRespVO> authenticationCompany(@RequestBody CompanyCreateReqVO createReqVO) {
        CompanyRespVO companyRespVO=new CompanyRespVO();
        EnterpriseCompanyDO enterpriseCompanyDO=companyService.applyAuthenticationCompany(createReqVO);
        BeanUtils.copyProperties(enterpriseCompanyDO,companyRespVO);
            return success(companyRespVO);
    }

    @PutMapping("/updatePhone")
    @ApiOperation("更新企业员工手机号")
    public CommonResult<Boolean> updatePhone(@RequestBody CompanyUpdatePhoneReqVO reqVO) {
        companyService.updatePhone(reqVO);
        return success(true);
    }


    @GetMapping("/checkCreditCode")
    @ApiOperation("判断企业是否存在")
    @ApiImplicitParam(name = "creditCode", value = "统一信用代码", required = true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<Boolean> checkCreditCode(@RequestParam("creditCode") String  creditCode) {
        return success(companyService.checkCreditCode(creditCode));
    }

    @GetMapping("/isAuthentication")
    @ApiOperation("判断企业是否已经认证")
    @TenantIgnore
    @PreAuthenticated
    @DataPermission(enable = false)
    public CommonResult<Boolean> isAuthentication() {
        LoginUser loginUser=SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null||loginUser.getCompanyId()==null){
            return success(false);
        }
        EnterpriseCompanyDO companyDO=companyService.getCompany(loginUser.getCompanyId());
        return success(companyDO.getAuthorizedStatus().equals("authorized")||companyDO.getAuthorizedStatus().equals("changeing"));
    }

    @PostMapping("/user-page")
    @ApiOperation("获得企业用户分页")
    public CommonResult<PageResult<UserPageItemRespDTO>> getCompanyUserPage(@RequestBody UserPageReqDTO pageVO) {
        return success(adminUserApi.getCompanyUsersPage(pageVO));
    }
    @PostMapping("/user-get")
    @ApiOperation("获得企业用户")
    public CommonResult<CompanyUserRespVO> getCompanyUserPage() {
        try{
            AdminUserRespDTO adminUserRespDTO= adminUserApi.getUser(SecurityFrameworkUtils.getLoginUserId());
            CompanyUserRespVO companyUserRespVO=new CompanyUserRespVO();
            if(SecurityFrameworkUtils.getLoginUser().getCompanyId()!=null){
                EnterpriseCompanyDO enterpriseCompanyDO=companyService.getCompany(SecurityFrameworkUtils.getLoginUser().getCompanyId());
                BeanUtils.copyProperties(enterpriseCompanyDO,companyUserRespVO);
            }
            companyUserRespVO.setTelephony(adminUserRespDTO.getTelephony());
            companyUserRespVO.setEmail(adminUserRespDTO.getEmail());
            companyUserRespVO.setUserId(SecurityFrameworkUtils.getLoginUserId());
            companyUserRespVO.setDeptName(adminUserRespDTO.getDeptName());
            companyUserRespVO.setRemark(adminUserRespDTO.getRemark());
            companyUserRespVO.setNickname(adminUserRespDTO.getNickname());
            companyUserRespVO.setJob(adminUserRespDTO.getPosition());
            companyUserRespVO.setUnrealFlag(adminUserRespDTO.getUnrealFlag());
            return success(companyUserRespVO);
        }catch (Exception e){
            throw exception(USER_NOT_EXISTS);
        }
    }


    @PutMapping("/updateCompanyUserInfo")
    @ApiOperation("更新企业用户信息")
    public CommonResult<Boolean> updateCompanyUserInfo( @RequestBody UserUpateReqDTO updateReqVO) {
        Long userCountByMobile = adminUserApi.getUserCountByMobile(updateReqVO.getMobile());
        if(userCountByMobile>0){
            return error("该手机号已存在");
        }
        updateReqVO.setId(SecurityFrameworkUtils.getLoginUserId());
        updateReqVO.setUserName(updateReqVO.getMobile());
        updateReqVO.setPassword(updateReqVO.getMobile());
        updateReqVO.setMobile(EncryptionUtil.desEncrypt(updateReqVO.getMobile()));
        adminUserApi.updateSonUser(updateReqVO);
        return success(true);
    }


    @PutMapping("/user-update")
    @ApiOperation("更新企业用户信息")
    public CommonResult<Boolean> updateCompanyUser( @RequestBody UserUpateReqDTO updateReqVO) {
        AdminUserRespDTO adminUserRespDTO= adminUserApi.getUser(SecurityFrameworkUtils.getLoginUserId());
        updateReqVO.setId(SecurityFrameworkUtils.getLoginUserId());
        updateReqVO.setDeptId(adminUserRespDTO.getDeptId());
        updateReqVO.setMobile(adminUserRespDTO.getMobile());
        updateReqVO.setPostIds(adminUserRespDTO.getPostIds());
        updateReqVO.setUserName(adminUserRespDTO.getUserName());
        adminUserApi.updateSonUser(updateReqVO);
        return success(true);
    }

    @PutMapping("/user-son-update")
    @ApiOperation("更新企业用户信息")
    public CommonResult<Boolean> updateCompanySonUser( @RequestBody UserUpateReqDTO updateReqVO) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO adminUserRespDTO= adminUserApi.getUser(loginUserId);
        if(updateReqVO.getId().equals(loginUserId)){
            updateReqVO.setDeptId(adminUserRespDTO.getDeptId());
//        updateReqVO.setMobile(adminUserRespDTO.getMobile());
            updateReqVO.setPostIds(adminUserRespDTO.getPostIds());
//        updateReqVO.setUserName(adminUserRespDTO.getUserName());
        }
        adminUserApi.updateSonUser(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/user-delete")
    @ApiOperation("删除企业用户信息")
    public CommonResult<Boolean> deleteCompanyUser(@RequestParam("id") Long id) {
        adminUserApi.deleteUser(id);
        return success(true);
    }
    @PostMapping("/user-create")
    @ApiOperation("创建企业用户信息")
    public CommonResult<Long> createCompanyUser( @RequestBody UserCreateReqDTO createReqVO) {
        return success(adminUserApi.createCompanySonUser(createReqVO,SecurityFrameworkUtils.getLoginUser().getTenantId()));
    }
    @PostMapping("/isRealName")
    @ApiOperation("三要素认证")
    @TenantIgnore
    public CommonResult<Map<String,Object>> isRealName(@RequestBody RealNameReqVo realNameReqVo) {
        Map<String,Object> flag= IdAuthenticationUtils.idAuthentication(realNameReqVo.getCardNo(),realNameReqVo.getPhone(),realNameReqVo.getUserName());
        EnterpriseCompanyDO enterpriseCompanyDO=companyService.getCompany(realNameReqVo.getCardNo(),realNameReqVo.getPhone(),realNameReqVo.getUserName());
        if(enterpriseCompanyDO!=null) {
            if(!flag.isEmpty()){
                if(flag.get("code").equals("1")){
                    enterpriseCompanyDO.setIsRealName("yes");
                }else {
                    enterpriseCompanyDO.setIsRealName("no");
                }
            }
            companyService.updateCompanyIsRealName(enterpriseCompanyDO.getId(), enterpriseCompanyDO.getIsRealName());
        }
        return success(flag);
    }
}
